<template>
  <div v-if="userStore.token">
    <el-dropdown trigger="hover" placement="bottom-end">
      <div class="avatar-wrapper">
        <el-avatar :size="40" :src="userStore.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"/>
        <span class="username">{{ userStore.username }}</span>
        <el-icon><arrow-down /></el-icon>
      </div>
      
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item>
            <div class="user-info">
              <el-avatar :size="60" :src="userStore.avatar"/>
              <div class="user-details">
                <div class="name">{{ userStore.username }}</div>
                <div class="role">{{ userStore.roleName }}</div>
              </div>
            </div>
          </el-dropdown-item>
          <el-dropdown-item divided @click="goToProfile">
            <el-icon><user /></el-icon> 个人信息
          </el-dropdown-item>
          <el-dropdown-item divided @click="handleLogout">
            <el-icon><switch-button /></el-icon> 退出登录
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup>
import { useUserStore } from '@/store/user'
import { useRouter } from 'vue-router'
import { employeeLogout } from '@/api/employee'

const userStore = useUserStore()
const router = useRouter()

const goToProfile = () => {
  router.push('/profile')
}

const handleLogout = async () => {
  // 调用后端退出接口，无论成功与否都继续执行后续操作
  employeeLogout().finally(() => {
    // 清除本地 token 和用户信息
    userStore.setToken('')
    userStore.setUserInfo({})
    // 跳转到登录页
    router.push('/login')
  })
}
</script>

<style scoped>
.avatar-wrapper {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0 10px;
}

.username {
  margin: 0 8px;
  font-size: 14px;
}

.user-info {
  display: flex;
  align-items: center;
  padding: 10px;
  min-width: 200px;
}

.user-details {
  margin-left: 15px;
}

.name {
  font-weight: 500;
  margin-bottom: 5px;
}

.role {
  font-size: 12px;
  color: #909399;
}
</style>